package com.atguigu.util;


import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Component
public class QiniuCloudUtil {

    static final String QiniuCloud_accessKey = "2Rai0qZunVua9ouyX1TnmiUtRCnuy8N8wjAexkdz";

    static  final String QiniuCloud_secretKey = "0VktrYKzjvKlpibOl-ughFsNI0nVVE8NnuT0NsAF";

    static final String QiniuCloud_bucket = "edu-test101";

    static  final String QiniuCloud_domainName = "http://sbf0bh069.hn-bkt.clouddn.com";

    static final String customSuffix = ".jpg";//定义图片保存后的后缀


    public static Object QiniuCloudUploadImage(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return "文件为空";
        } else if (file.getSize() > 1024 * 1024 * 2) {
            return "文件大于2M";
        }
        //获取图片后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //允许上传的图片格式集合
        String[] suffixes = new String[]{".bmp", ".jpeg", ".jpg", ".png"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for (String string : suffixes) {
            if (string.equals(suffix)) {
                bool = true;
                break;
            }
        }
        if (!bool) {
            return "图片格式错误";
        }
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        String accessKey = QiniuCloud_accessKey;
        String secretKey = QiniuCloud_secretKey;
        String bucket = QiniuCloud_bucket;

        byte[] bytes = file.getBytes();
        String imageName = DigestUtils.md5DigestAsHex(bytes);//将图片md5的值作为图片名，避免重复图片浪费空间
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = imageName + customSuffix;//图片保存到七牛云后的文件名

        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                uploadManager.put(byteInputStream, key, upToken, null, null);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println("七牛云ERROR:" + r.toString());
                try {
                    System.err.println("七牛云ERROR:" + r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }

        return QiniuCloud_domainName + '/' + key;
    }

    public static Object QiniuCloudDownloadImage(String fileName) {
        String fileUrl = String.format("%s/%s", QiniuCloud_domainName, fileName);
        return fileUrl;
    }

    /**
     * 从七牛云删除图片
     *
     * @param fileNameList 图片名集合
     * @return 返回每张图片的删除结果
     */
    public static Object QiniuCloudDeleteImage(String[] fileNameList) {
        //用Json格式传数组时直接传["xxx", "xxx", "xxx", "xxx"]
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //生成凭证
        String accessKey = QiniuCloud_accessKey;
        String secretKey = QiniuCloud_secretKey;
        String bucket = QiniuCloud_bucket;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //创建一个用来接收删除结果的集合
        List<String> list = new ArrayList<>();
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, fileNameList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < fileNameList.length; i++) {
                BatchStatus status = batchStatusList[i];
                if (status.code == 200) {//成功返回文件名+true并添加进集合
                    list.add("{fileName:" + fileNameList[i] + ",deleteResult:true}");
                } else {//失败返回文件名+false并添加进集合
                    list.add("{fileName:" + fileNameList[i] + ",deleteResult:false}");
                }
            }
        } catch (QiniuException ex) {
            System.err.println("七牛云ERROR:" + ex.response.toString());
        }
        return list;
    }


}
